#include "DTD.h"
#include <string.h>

DTD::DTD()
{
}

int DTD::addElement(char * name, ElementDTD * e)
{
    /* Checking that element e doesn't already exist in the map */
	pair< map<string , ElementDTD*>::iterator , bool> ret;
    ret=elems.insert (pair<string, ElementDTD*>(name,e) );
    if (ret.second==false)
    {
        return -1;
    }

	return 0;
}

void DTD::addAttribute(AttributeDTD* att)
{
    atts.push_back(att);
}

ElementDTD* DTD::getElementByName(string name) const
{
    map<string,ElementDTD*>::const_iterator it;
    it = elems.find(name);

    if ( it == elems.end() )
    {
        return NULL; // the element named name doesn't exist
    }

    return it->second;
}


int DTD::makeDTD()
{
    vector<AttributeDTD*>::iterator it;

    for(it = atts.begin() ; it != atts.end() ; ++it)
    {
        /* for each attribute, we check that element corresponding exists */
        ElementDTD* elem = getElementByName( (*it)->getElementAssociated() );
        if(elem == NULL)
        {
            printf("Element named \"%s\" doesn't exist\n", (*it)->getElementAssociated().c_str() );
        }

        else /* we check that this attribute is unique for this element*/
        {
            int ret = elem->addAttribute( *it );
            if (ret == -1)
                return -1;
        }
    }

    return 0;
}


void DTD::display() const
{
    printf("\n#### Affichage de la structure de la DTD qui contient %d elements\n\n", elems.size());

    map<string,ElementDTD*>::const_iterator it;

    // displaying each element
    for ( it=elems.begin() ; it != elems.end(); it++ )
    {
        (*it).second->display();
        printf("\n\n");
    }

    printf("##########\n");
}


